//
//  BookRecommendTableViewController.m
//  XMLY
//
//  Created by 曾杰 on 15/11/10.
//  Copyright © 2015年 曾杰. All rights reserved.
//

#import "BookRecommendTableViewController.h"
#import "PKRequestManager.h"
#import "BooklistCell.h"
#import "UIImageView+WebCache.h"
#import "SoundBookCell.h"
#import "SDCycleScrollView.h"
#import "MoreListViewController.h"
#import "MusicPlayViewController.h"
#import "TopListViewController.h"
#import "MusicDetailViewController.h"
#import "CheckNetConnect.h"
#import "NetConnectView.h"
@interface BookRecommendTableViewController ()<SDCycleScrollViewDelegate,UITableViewDataSource,UITableViewDelegate>
@property (nonatomic, strong) NSMutableArray *dataArr;//数据数组
@property (nonatomic, strong) NSMutableArray *sectionArr;//分区数组
@property (nonatomic, strong) UITableView *bookRecom;
@property (nonatomic, strong) NetConnectView *connectView;
@end

@implementation BookRecommendTableViewController


-(NSMutableArray *)dataArr
{
    if (_dataArr == nil) {
        self.dataArr = [NSMutableArray arrayWithCapacity:0];
    }
    return _dataArr;
}

-(NSMutableArray *)sectionArr
{
    if (_sectionArr == nil) {
        self.sectionArr = [NSMutableArray array];
    }
    return _sectionArr;
}

//配置数据
- (void)configureData
{
    [PKRequestManager requestWithType:GET urlString:_urlStr parDic:nil finish:^(NSData *data) {
       
       

            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves) error:nil];
        
                self.sectionArr = dic[@"categoryContents"][@"list"];
                self.dataArr = dic[@"focusImages"][@"list"];
                self.bookRecom.tableHeaderView = [self tableViewHeader];
                [self.bookRecom reloadData];
        

    } error:^(NSError *error) {
        
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.bookRecom = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-100) style:(UITableViewStylePlain)];
    self.bookRecom.dataSource = self;
    self.bookRecom.delegate = self;
    [self.bookRecom registerClass:[SoundBookCell class] forCellReuseIdentifier:@"bookRecomCell"];
    [self.bookRecom registerClass:[BooklistCell class] forCellReuseIdentifier:@"bookListCell"];
    [self checkNetConnectState];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source
//分区数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.sectionArr.count;
}
//行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray *arr = self.sectionArr[section][@"list"];
    return arr.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        BooklistCell *cell = [tableView dequeueReusableCellWithIdentifier:@"bookListCell" forIndexPath:indexPath];
        cell.titleLabel.text = self.sectionArr[indexPath.section][@"list"][0][@"title"];
        cell.introLabel.text = self.sectionArr[indexPath.section][@"list"][0][@"subtitle"];
        [cell.picImageView setImage:[UIImage imageNamed:@"jiangbei"]];
        cell.picImageView.layer.cornerRadius = 30;
        cell.picImageView.layer.masksToBounds = YES;
        return cell;
    }
    else
    {
        SoundBookCell *cell = [tableView dequeueReusableCellWithIdentifier:@"bookRecomCell" forIndexPath:indexPath];
        [cell.picImageView sd_setImageWithURL:[NSURL URLWithString:self.sectionArr[indexPath.section][@"list"][indexPath.row][@"albumCoverUrl290"]]];
        cell.titleLabel.text = self.sectionArr[indexPath.section][@"list"][indexPath.row][@"title"];
        cell.introLabel.text = [@"by " stringByAppendingString:self.sectionArr[indexPath.section][@"list"][indexPath.row][@"nickname"] ];
        CGFloat playCount = [self.sectionArr[indexPath.section][@"list"][indexPath.row][@"playsCounts"] floatValue];
        if (playCount < 10000) {
            cell.playCountLabel.text = [NSString stringWithFormat:@"%.0f",playCount];
        }else
        {
            cell.playCountLabel.text = [[NSString stringWithFormat:@"%.0f",playCount / 10000.0]stringByAppendingString:@"万"];
        }
        CGFloat tracks = [self.sectionArr[indexPath.section][@"list"][indexPath.row][@"tracksCounts"] floatValue];
        cell.tracksCounts.text = [[NSString stringWithFormat:@"%.0f",tracks]stringByAppendingString:@"集"];
        return cell;
    }
}
//行高
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 80;
    }else
    {
        return 100;
    }
}
//区头视图
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 50)];
    view.backgroundColor = [UIColor whiteColor];
    UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(30, 10, 150, 30)];
    titleLabel.text = self.sectionArr[section][@"title"];
    [view addSubview:titleLabel];
    if (section == 0) {
        return view;
    }else
    {
        UILabel *moreLabel = [[UILabel alloc]initWithFrame:CGRectMake(SCREEN_WIDTH-160, 10, 150, 30)];
        moreLabel.text = @"更多 >";
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(didClickTap:)];
        moreLabel.userInteractionEnabled = YES;
        moreLabel.tag = section;
        [moreLabel addGestureRecognizer:tap];
        moreLabel.textAlignment = NSTextAlignmentRight;
        [view addSubview:moreLabel];
    }
    return view;
}

//区头高度
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 50;
}
//表头轮播图
- (UIView *)tableViewHeader
{
    
    SDCycleScrollView *ycleScrollView = [[SDCycleScrollView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT / 3-20)];
    ycleScrollView.delegate = self;
    NSMutableArray *arr = [NSMutableArray array];
    for (NSDictionary *dic in self.dataArr) {
        [arr addObject:dic[@"pic"]];
    }
    ycleScrollView.imageURLStringsGroup = arr;
    return ycleScrollView;
}
//点击轮播图跳转
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index
{
    if (self.dataArr[index][@"trackId"]!= nil) {
        MusicPlayViewController *playViewVC = [[MusicPlayViewController alloc]init];
        playViewVC.trackId =  self.dataArr[index][@"trackId"];
        playViewVC.index = index;
        [self presentViewController:playViewVC animated:YES completion:nil];
    }else
    {
        MusicDetailViewController *detailVC = [[MusicDetailViewController alloc]init];
        detailVC.albumId = self.dataArr[index][@"albumId"];
        [self presentViewController:detailVC animated:YES completion:nil];
    }
    
}
//点击cell跳转
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger albunId = [self.sectionArr[indexPath.section][@"list"][indexPath.row][@"albumId"] integerValue];
    if (indexPath.section == 0 && indexPath.row == 0) {
        TopListViewController *topListVC = [[TopListViewController alloc]init];
        topListVC.key = @"ranking%3Aalbum%3Aplayed%3A1%3A3";
        topListVC.titleStr = self.sectionArr[indexPath.section][@"list"][indexPath.row][@"title"];
        [self presentViewController:topListVC animated:YES completion:nil];
    }
    else
    {
        MusicDetailViewController  *playListVC = [[MusicDetailViewController alloc]init];
        playListVC.albumId = [NSString stringWithFormat:@"%ld",(long)albunId];
        [self presentViewController:playListVC animated:YES completion:nil];
    }
}
//点击更多跳转
- (void)didClickTap:(UITapGestureRecognizer *)tap
{
    MoreListViewController *moreVC = [[MoreListViewController alloc]init];
    moreVC.categoryId = @"3";
    if (tap.view.tag == 0) {
        
    }if (tap.view.tag == 1)
    {
        moreVC.tagName = @"";
        moreVC.titleStr = self.sectionArr[tap.view.tag][@"title"];
    }if (tap.view.tag == 2)
    {
        moreVC.tagName = @"%E6%B5%AA%E6%BC%AB%E8%A8%80%E6%83%85";
        moreVC.titleStr = self.sectionArr[tap.view.tag][@"title"];
    }if (tap.view.tag == 3)
    {
        moreVC.tagName = @"%E6%81%90%E6%80%96%E6%82%AC%E7%96%91";
        moreVC.titleStr = self.sectionArr[tap.view.tag][@"title"];
    }if (tap.view.tag == 4)
    {
        moreVC.tagName = @"%E7%8E%84%E5%B9%BB%E5%A5%87%E5%B9%BB";
        moreVC.titleStr = self.sectionArr[tap.view.tag][@"title"];
    }if (tap.view.tag == 5)
    {
        moreVC.tagName = @"%E5%8E%86%E5%8F%B2%E5%86%9B%E4%BA%8B";
        moreVC.titleStr = self.sectionArr[tap.view.tag][@"title"];
    }if (tap.view.tag == 6)
    {
        moreVC.tagName = @"%E5%8F%A4%E8%A8%80%E5%AE%AB%E6%96%97";
        moreVC.titleStr = self.sectionArr[tap.view.tag][@"title"];
    }if (tap.view.tag == 7)
    {
        moreVC.tagName = @"%E6%8E%A2%E6%A1%88%E6%8E%A8%E7%90%86";
        moreVC.titleStr = self.sectionArr[tap.view.tag][@"title"];
    }
    [self presentViewController:moreVC animated:YES completion:nil];
}

- (void)checkNetConnectState{
    
    BOOL netState = [[CheckNetConnect shareConnect] netConnectState];
    if (netState == YES) {
        NSLog(@"开始刷新数据");
        [self.view addSubview:self.bookRecom];
        _connectView.frame = CGRectMake(0, - SCREEN_HEIGHT - 20, SCREEN_WIDTH, SCREEN_HEIGHT - 50) ;
        [_connectView.retryBtn addTarget:self action:@selector(retryRequest) forControlEvents:(UIControlEventTouchUpInside)];
        [self configureData];
        
    }else{
        
        _connectView = [[NetConnectView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 50)];
        [_connectView.retryBtn addTarget:self action:@selector(retryRequest) forControlEvents:(UIControlEventTouchUpInside)];
        
        [self.view addSubview:_connectView];
    }
    
}

// 重新请求数据
- (void)retryRequest{
    NSLog(@"重新刷新数据");
    [self checkNetConnectState];
}

//设置区头随tableView滑动而滑动
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
    if (scrollView==self.bookRecom) {
        CGFloat sectionHeight = 30;
        if (scrollView.contentOffset.y<=sectionHeight&&scrollView.contentOffset.y>0) {
            scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
        }
        else if (scrollView.contentOffset.y>=sectionHeight)
        {
            scrollView.contentInset = UIEdgeInsetsMake(-sectionHeight, 0, 0, 0);
        }
    }
    
}


@end
